<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入分类名称"
            clearable
            prefix-icon="el-icon-collection-tag"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="isDeleted">
          <el-select v-model="queryParams.isDeleted" placeholder="请选择状态" clearable style="width: 120px">
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="box-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span class="card-title">题目分类列表</span>
        <div class="action-buttons">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['question:category:add']"
          >新增</el-button>
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['question:category:edit']"
          >修改</el-button>
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['question:category:remove']"
          >删除</el-button>
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['question:category:export']"
          >导出</el-button>
          <el-button
            :type="showDeleted ? 'warning' : 'info'"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="toggleRecycleBin"
          >{{ showDeleted ? '返回列表' : '回收站' }}</el-button>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="categoryList"
        @selection-change="handleSelectionChange"
        border
        stripe
        highlight-current-row
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="分类ID" align="center" prop="id" width="80" />
        <el-table-column label="分类名称" align="left" prop="name" min-width="200">
          <template slot-scope="scope">
            <div class="category-name">
              <i class="el-icon-collection-tag" />
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="isDeleted" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.isDeleted"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template slot-scope="scope">
            <template v-if="!showDeleted">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['question:category:edit']"
              >修改</el-button>
              <el-divider direction="vertical"></el-divider>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['question:category:remove']"
              >删除</el-button>
            </template>
            <template v-else>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-refresh"
                @click="handleRestore(scope.row)"
                v-hasPermi="['question:category:edit']"
              >恢复</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="状态" prop="isDeleted">
          <el-select v-model="form.isDeleted" placeholder="请选择状态" style="width: 100%">
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from "@/api/question/category";

export default {
  name: "Category",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分类表格数据
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        isDeleted: '0'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ]
      },
      // 显示回收站
      showDeleted: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询分类列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        isDeleted: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.isDeleted = this.showDeleted ? '1' : '0';
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加分类";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCategory(id).then(response => {
        this.form = response.data;
        this.form.isDeleted = parseInt(this.form.isDeleted);
        this.open = true;
        this.title = "修改分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;

        // 添加 loading
        const loading = this.$loading({
          lock: true,
          text: '提交中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        // 检查分类名称是否已存在
        listCategory({
          name: this.form.name,
          pageSize: 1
        }).then(response => {
          const existingCategory = response.rows.find(item => 
            item.name === this.form.name && item.id !== this.form.id
          );

          if (existingCategory) {
            loading.close();
            this.$modal.msgError("分类名称已存在");
            return;
          }

          // 不存在重复，继续提交
          const request = this.form.id ? updateCategory(this.form) : addCategory(this.form);
          
          request.then(response => {
            loading.close();
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          }).catch(() => {
            loading.close();
            this.$modal.msgError("操作失败");
          });
        }).catch(() => {
          loading.close();
          this.$modal.msgError("操作失败");
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认永久删除该分类？该操作不可恢复！').then(function() {
        return delCategory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('question/category/export', {
        ...this.queryParams
      }, `category_${new Date().getTime()}.xlsx`)
    },
    /** 切换回收站显示状态 */
    toggleRecycleBin() {
      this.showDeleted = !this.showDeleted;
      this.queryParams.isDeleted = this.showDeleted ? '1' : '0';
      this.handleQuery();
    },
    /** 恢复按钮操作 */
    handleRestore(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认恢复分类编号为"' + id + '"的数据项？').then(async () => {
        // 获取分类详细信息
        const response = await getCategory(id);
        // 修改状态为0（正常）
        const data = {
          ...response.data,
          isDeleted: 0
        };
        // 调用修改接口
        return updateCategory(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("恢复成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.search-card {
  margin-bottom: 16px;
  border-radius: 4px;
}

.box-card {
  margin-bottom: 16px;
  border-radius: 4px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2f3d;
}

.action-buttons {
  float: right;
}

.category-name {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.category-name i {
  margin-right: 8px;
  color: #409EFF;
}

.el-card {
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08) !important;
}

.el-card :deep(.el-card__header) {
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

.el-table {
  margin: 8px 0;
}

.el-table :deep(th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
}

.el-table :deep(td) {
  padding: 8px 0;
}

.el-tag {
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

.el-divider--vertical {
  margin: 0 8px;
}

/* 表格hover效果 */
.el-table :deep(tbody tr:hover) td {
  background-color: #ecf5ff !important;
}

/* 输入框图标颜色 */
.el-input :deep(.el-input__icon) {
  color: #909399;
}

/* 表单项间距 */
.el-form-item {
  margin-bottom: 16px;
}

.el-button--info.is-plain {
  color: #909399;
  background: #f4f4f5;
  border-color: #d3d4d6;
}

.el-button--info.is-plain:hover {
  color: #409EFF;
  background: #ecf5ff;
  border-color: #b3d8ff;
}
</style>
